<template>
  <div class="image-marker">
    <div class="image-container">
      <!-- 显示图片 -->
      <img ref="image" :src="imageUrl" @load="handleImageLoad" />
      <!-- 鼠标点击标记点 -->
      <div v-if="showMarker" class="marker" :style="{ left: markerPosition.x + 'px', top: markerPosition.y + 'px' }" @click="addPoint"></div>
    </div>
    <button @click="exportImage">导出带标记的图片</button>
  </div>
</template>

<script>
import {base64ToFile} from "../utils";
import uploadOssFn from "../utils/uploadOssFn";

export default {
  props: {
    imageUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageLoaded: false,
      showMarker: false,
      markerPosition: {x: 0, y: 0},
      points: [] // 存储所有标记点的坐标
    };
  },
  methods: {
    // 图片加载完成后的回调
    handleImageLoad() {
      this.imageLoaded = true;
      this.$refs.image.setAttribute("crossOrigin",'anonymous');
    },
    // 添加标记点
    addPoint(event) {
      // console.log(!this.imageLoaded)
      // if (!this.imageLoaded) return;
      // const rect = this.$refs.image.getBoundingClientRect();
      // const x = event.clientX - rect.left;
      // const y = event.clientY - rect.top;
      // console.log(x, y)
      // this.points.push({x, y});
      // this.showMarker = false; // 隐藏标记点
    },
    // 显示标记点
    showMarkerPoint(event) {
      if (!this.imageLoaded) return;
      const rect = this.$refs.image.getBoundingClientRect();
      this.markerPosition = {
        x: event.clientX - rect.left - 10, // 调整标记点的位置
        y: event.clientY - rect.top - 10
      };
      this.showMarker = true;
    },
    // 导出带标记的图片
    exportImage() {
      if (!this.imageLoaded) return;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = this.$refs.image.width;
      canvas.height = this.$refs.image.height;
      ctx.drawImage(this.$refs.image, 0, 0);
      [this.markerPosition].forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 10, 0, 2 * Math.PI);
        ctx.fillStyle = 'red';
        ctx.fill();
      });
      // 导出图片
      const imageDataURL = canvas.toDataURL();
      const timestamp = Date.now();
      const randomDigits = Math.floor(10000 + Math.random() * 90000); // 生成 5 位随机数
      const randomName = `${timestamp}${randomDigits}`;
      const file = base64ToFile(imageDataURL, `${randomName}.png`)
      // oss对象储存上传函数
      uploadOssFn([file], 'images', 5).then(res => {
        console.log(res[0].url)
      })
    }
  },
  mounted() {
    // 监听鼠标点击事件，在图片上显示标记点
    this.$refs.image.addEventListener('click', this.showMarkerPoint);
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$refs.image.removeEventListener('click', this.showMarkerPoint);
  }
};
</script>

<style scoped>
.image-container {
  position: relative;
}

.marker {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: red;
  border-radius: 50%;
  cursor: pointer;
}
</style>